import React, { useState } from "react";
import axios from "axios";
import "./Login.css"; // 引入样式文件

/**
 * 登录组件 - 实现京东风格的登录页面
 * 包含账户登录表单、错误处理、加载状态等功能
 */
const Login = () => {
    // 使用React的useState钩子管理表单数据和组件状态
    const [formData, setFormData] = useState({
        username: "", // 用户名/邮箱/手机号
        password: "", // 密码
        captcha: "", // 验证码
    });
    const [loading, setLoading] = useState(false); // 加载状态
    const [error, setError] = useState(""); // 错误信息
    const [loginMode, setLoginMode] = useState("password"); // 登录模式：password 或 captcha
    const [captchaCode, setCaptchaCode] = useState(""); // 验证码图片

    /**
     * 处理表单输入变化
     * @param {Object} e - 事件对象
     */
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        // 更新对应的表单字段
        setFormData((prev) => ({
            ...prev,
            [name]: value,
        }));
    };

    /**
     * 生成验证码
     */
    const generateCaptcha = () => {
        const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        let result = "";
        for (let i = 0; i < 4; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        setCaptchaCode(result);
    };

    /**
     * 切换登录模式
     */
    const toggleLoginMode = () => {
        setLoginMode(loginMode === "password" ? "captcha" : "password");
        setFormData((prev) => ({ ...prev, captcha: "" }));
        if (loginMode === "password") {
            generateCaptcha();
        }
    };

    /**
     * 处理表单提交
     * @param {Object} e - 事件对象
     */
    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault(); // 阻止表单默认提交行为
        setLoading(true); // 开始加载
        setError(""); // 清空错误信息

        // 验证码模式下的验证
        if (
            loginMode === "captcha" &&
            formData.captcha.toUpperCase() !== captchaCode
        ) {
            setError("验证码错误");
            setLoading(false);
            return;
        }

        try {
            // 发送POST请求到登录接口
            const response = await axios.post("/api/login", formData);

            // 登录成功：存储token到localStorage
            localStorage.setItem("authToken", response.data.token);
            localStorage.setItem("username", formData.username); // 新增：存储用户名

            // 跳转到首页
            window.location.href = "/home/index/indexx";
        } catch (err: unknown) {
            // 登录失败：显示错误信息
            const error = err as { response?: { data?: { message?: string } } };
            setError(error.response?.data?.message || "用户名或密码错误");
        } finally {
            setLoading(false); // 结束加载
        }
    };

    // 组件渲染
    return (
        <div className="login-container">
            {/* 登录框容器 */}
            <div className="login-wrapper">
                {/* 登录表单盒子 */}
                <div className="login-box">
                    {/* 登录头部 - 包含选项卡 */}
                    <div className="login-header">
                        <div className="login-tabs">
                            <span className="active">账户登录</span>
                            <span>二维码登录</span>
                        </div>
                    </div>

                    {/* 错误信息显示 */}
                    {error && (
                        <div className="error-message">
                            <i className="icon-warning"></i>
                            <span>{error}</span>
                        </div>
                    )}

                    {/* 登录表单 */}
                    <form onSubmit={handleSubmit}>
                        {/* 用户名输入组 */}
                        <div className="form-group">
                            <input
                                type="text"
                                name="username"
                                placeholder="用户名/邮箱/手机号"
                                value={formData.username}
                                onChange={handleChange}
                                required
                            />
                        </div>

                        {/* 密码输入组 */}
                        <div className="form-group">
                            <input
                                type="password"
                                name="password"
                                placeholder="请输入密码"
                                value={formData.password}
                                onChange={handleChange}
                                required
                            />
                        </div>

                        {/* 验证码输入组 */}
                        {loginMode === "captcha" && (
                            <div className="form-group captcha-group">
                                <input
                                    type="text"
                                    name="captcha"
                                    placeholder="请输入验证码"
                                    value={formData.captcha}
                                    onChange={handleChange}
                                    required
                                    style={{ width: "60%" }}
                                />
                                <button
                                    type="button"
                                    onClick={generateCaptcha}
                                    style={{
                                        width: "35%",
                                        height: "40px",
                                        border: "1px solid #ddd",
                                        borderRadius: "4px",
                                        cursor: "pointer",
                                        fontSize: "16px",
                                        fontWeight: "bold",
                                        background: "#f5f5f5",
                                        color: "#333",
                                    }}
                                >
                                    {captchaCode || "点击生成"}
                                </button>
                            </div>
                        )}

                        {/* 登录选项 - 记住我和忘记密码 */}
                        <div className="login-options">
                            <label className="remember-me">
                                <input type="checkbox" />
                                <span>记住我</span>
                            </label>
                            <a href="/forgot" className="forgot-password">
                                忘记密码？
                            </a>
                        </div>

                        {/* 验证码切换按钮 */}
                        <div className="captcha-toggle">
                            <button
                                type="button"
                                onClick={toggleLoginMode}
                                style={{
                                    background: "none",
                                    border: "1px solid #ddd",
                                    padding: "8px 16px",
                                    borderRadius: "4px",
                                    cursor: "pointer",
                                    fontSize: "14px",
                                    marginBottom: "16px",
                                }}
                            >
                                {loginMode === "password"
                                    ? "切换到验证码登录"
                                    : "切换到密码登录"}
                            </button>
                        </div>

                        {/* 登录按钮 */}
                        <button
                            type="submit"
                            className="login-btn"
                            disabled={loading} // 加载时禁用按钮
                        >
                            {loading ? "登录中..." : "登 录"}
                        </button>

                        {/* 注册链接 */}
                        <div className="register-link">
                            <span>还没有账号？</span>
                            <a href="/register">免费注册</a>
                        </div>

                        {/* 第三方登录 */}
                        <div className="third-party-login">
                            <div className="divider">
                                <span>其他登录方式</span>
                            </div>
                            <div className="login-icons">
                                <a href="#">
                                    <i className="icon-wechat"></i>
                                </a>
                                <a href="#">
                                    <i className="icon-qq"></i>
                                </a>
                                <a href="#">
                                    <i className="icon-weibo"></i>
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default Login;
